import {getToken} from "@/lib/auth";

export default class ApiProxy {

    static async getHeaders(requireAuth) {
        let headers = {
            "Content-Type": "application/json",
            "Accept": "application/json"
        }
        const authToken = await getToken();
        if (authToken && requireAuth) {
            headers["Authorization"] = `Bearer ${authToken}`;
        }
        return headers;
    }

    static async post(endpoint, object, requireAuth) {
        const jsonData = JSON.stringify(object);
        // 构建请求信息：请求方式、请求头、请求体
        const headers = await ApiProxy.getHeaders(requireAuth);
        const requestOptions = {
            method: "POST",
            headers: headers,
            body: jsonData,
        }
        // 向fastapi请求数据
        return await fetch(endpoint, requestOptions);
    }

    static async get(endpoint, requireAuth) {
        // 构建请求信息：请求方式、请求头、请求体
        const headers = await ApiProxy.getHeaders(requireAuth);
        const requestOptions = {
            method: "GET",
            headers: headers
        }
        // 向fastapi请求数据
        return await fetch(endpoint, requestOptions);
    }
}